<template>
  <div class="live-commodity">
    <search-table
            :url="listUrl"
            ref="searchtable"
            :columns="columns"
            :headParams="headParams"
            :defaultParams="userInfo.shopRoleCode == 'role:store:main' ? {} : defaultParams"
            :xLength="1200"
            :form="form">
      <!-- 搜索条件 -->
      <template slot="searchForm">
        <a-form layout="inline" :form="form">
          <a-form-item v-if="userInfo.shopRoleCode == 'role:store:main'" label="直播平台">
            <a-select
              showSearch
              allowClear
              style="width: 195px"
              :options="liveAppIdList"
              v-decorator="[
                'appId',
                {
                  initialValue: userInfo.shopRoleCode == 'role:store:main' ? '100000054' : (userInfo.shopRoleCode == 'role:store:branch' ? '100000055' : '')
                }
              ]"
              placeholder="请选择"
              @change="appIdChange">
            </a-select>
          </a-form-item>
          <a-form-item v-if="userInfo.shopRoleCode == 'role:store:main'" label="所属店铺">
            <a-select
              showSearch
              allowClear
              style="width: 195px"
              v-decorator="[
                'blongShop',
                {
                  initialValue: 1
                }
              ]"
              placeholder="请选择所属店铺"
              @change="blongShopChange">
              <a-select-option :value="1">本店直播</a-select-option>
              <a-select-option v-if="activeAppId == '100000055'" :value="2">其它店直播</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="商品名称">
            <a-input allowClear v-decorator="['name']" placeholder="请输入商品名称"></a-input>
          </a-form-item>
          <a-form-item label="商品ID">
            <a-input-number style="width: 200px" :precision="0" allowClear v-decorator="['goodsId']" placeholder="请输入商品ID"></a-input-number>
          </a-form-item>
          <a-form-item label="商品分组">
            <a-tree-select
                allowClear
                style="width:195px"
                :replaceFields="{children:'children', title:'groupName', key:'id', value: 'id' }"
                v-decorator="[
                  'goodsGroupId',
                ]"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="productGroupList"
                placeholder="请选择"
                tree-default-expand-all
                >
                <span slot="title" slot-scope="{ value }">
                    {{ value }}
                </span>
            </a-tree-select>
          </a-form-item>
          <a-form-item label="商品状态">
            <a-select
                    showSearch
                    allowClear
                    style="width: 195px"
                    :options="liveGoodsStatusList"
                    v-decorator="['productStatus']"
                    placeholder="请选择">
            </a-select>
          </a-form-item>
          <a-form-item label="审核状态">
            <a-select
                    showSearch
                    allowClear
                    style="width: 195px"
                    :options="wechatAuditStatusList"
                    v-decorator="['auditStatus']"
                    placeholder="请选择">
            </a-select>
          </a-form-item>
        </a-form>
      </template>
      <!-- 操作栏 -->
      <template slot="oprationRow">
        <permission authority="product:addProduct">
          <a-button type="primary" icon="plus" @click="creatLive()">增加商品</a-button>
        </permission>
        <permission authority="product:syncselect">
          <a-button @click="syncLive($refs.searchtable.selectedRows)">同步商品数据</a-button>
        </permission>
      </template>
      <!-- 表格行操作 -->
      <template slot="tableOperation" slot-scope="{ record }">
        <a-space>
          <permission authority="product:query" v-if="record.auditStatus == '1'">
            <span class="text-primary pointer" @click="checkLiveRoom(record, 'view')">查看</span>
          </permission>
          <permission authority="product:updateProduct" v-if="activeBlongShop == 1 && record.auditStatus != '1'">
            <span class="text-primary pointer" @click="checkLiveRoom(record, 'edit')">编辑</span>
          </permission>
          <permission authority="product:retryaudit" v-if="activeBlongShop == 1 && record.productStatus != '1'">
            <span class="text-primary pointer" @click="browseGoods(record, '1')">提交审核</span>
          </permission>
          <permission authority="product:resetaudit" v-if="record.productStatus == '1' && record.auditStatus == '1'">
            <span class="text-primary pointer" @click="browseGoods(record, '2')">撤回审核</span>
          </permission>
          <permission authority="product:deleteProduct" v-if="record.productStatus == '1' && record.auditStatus == '2'">
            <span class="text-danger pointer" @click="deleteLive(record)">下架并删除</span>
          </permission>
          <permission authority="product:deleteProduct" v-if="!record.auditStatus || record.auditStatus == '3'">
            <span class="text-danger pointer" @click="deleteLive(record)">删除</span>
          </permission>
        </a-space>
      </template>
    </search-table>
  </div>
</template>

<script>
  import { mapGetters } from "vuex";
  import { findDictNameByValue,createOptionsByDict } from '@/utils/dict'
  export default {
    name: "MarketingLiveCommodity",
    data() {
      return {
        listUrl: '/product/page', // 列表接口地址
        form: this.$form.createForm(this, {
          name: "table_search",
          mapPropsToFields: () => {
            let appId='',blongShop=1
            if(this.$route.query.appId){
              appId = this.$route.query.appId
            } else {
              if(this.$store.state.userInfo.shopRoleCode == 'role:store:main') {
                appId=createOptionsByDict('LIVE_APPID')[0] ? createOptionsByDict('LIVE_APPID')[0].value : '100000054'
              } else if(this.$store.state.userInfo.shopRoleCode == 'role:store:branch') {
                appId=createOptionsByDict('LIVE_APPID')[1] ? createOptionsByDict('LIVE_APPID')[1].value : '100000055'
              }
            }
            if(this.$route.query.blong) {
              blongShop = Number(this.$route.query.blong)
            } else {
              blongShop = 1
            }
            return {
              appId: this.$form.createFormField({
                ...appId,
                value: appId,
              }),
              blongShop: this.$form.createFormField({
                ...blongShop,
                value: blongShop,
              })
            }
          }
        }), // 搜索条件表单
        activeAppId: this.$route.query.appId || '100000054', // 当前直播平台，默认100000054
        activeBlongShop: 1, // 当前所属店铺，默认为本店
        headParams: { baseURL: '/goldenhome/gh/live/admin' }, // 列表接口域名
        defaultParams: {
          appId: this.$store.state.userInfo.shopRoleCode == 'role:store:branch' ? '100000055' : '',
          blongShop: this.$store.state.userInfo.shopRoleCode == 'role:store:branch' ? 1 : null
        }, // 列表默认携带参数
        handle: '', // 操作类型
        liveAppIdList: createOptionsByDict('LIVE_APPID'), // 直播平台
        liveGoodsStatusList: createOptionsByDict('LIVE_GOODS_AUDIT'), // 直播商品状态
        wechatAuditStatusList: createOptionsByDict('WECHAT_AUDIT_STATUS'), // 微信审核状态
        productGroupList:[], // 商品分组
        columns: [
          {
            title: "商品ID",
            dataIndex: "goodsId",
            width: 100,
            key: "goodsId",
          },
          {
            title: "商品名称",
            dataIndex: "name",
            width: 150,
            key: "name"
          },
          {
            title: "商品图片",
            dataIndex: "coverImgLocal",
            width: 125,
            key: "coverImgLocal",
            customRender: (text, record) => {
              if(text) {
                return <table-img src={text}/>
              } else {
                return <table-img src={record.coverImgUrl}/>
              }
            }
          },
          {
            title: "商品分组",
            dataIndex: "goodsGroupName",
            width: 125,
            key: "goodsGroupName"
          },
          {
            title: "价格类型",
            dataIndex: "priceType",
            width: 125,
            key: "priceType",
            customRender: (text, record) => findDictNameByValue('LIVE_GOODS_PRICE', text)
          },
          {
            title: "价格",
            dataIndex: "price",
            width: 160,
            key: "price",
            customRender: (text, record) => {
              let res = ''
              if(record.priceType == 1){
                res = (Number(record.price)/100).toFixed(2)+'元'
              } else if(record.priceType == 2) {
                res = (Number(record.price)/100).toFixed(2)+'元-'+(Number(record.price2)/100).toFixed(2)+'元'
              } else if(record.priceType == 3) {
                res = <span>市场价 {(Number(record.price)/100).toFixed(2)}元<br/>现价 {(Number(record.price2)/100).toFixed(2)}元</span>
              }
              return res
            }
          },
          {
            title: "添加方式",
            dataIndex: "thirdPartyTag",
            width: 125,
            key: "thirdPartyTag",
            customRender: (text, record) => findDictNameByValue('LIVE_GOOD_SOURCE', text)
          },
          {
            title: "添加时间",
            dataIndex: "createTime",
            width: 160,
            key: "createTime"
          },
          {
            title: "所属平台",
            dataIndex: "appName",
            width: 125,
            key: "appName"
          },
          {
            title: "所属机构",
            dataIndex: "orgName",
            width: 125,
            key: "orgName"
          },
          {
            title: "所属店铺",
            dataIndex: "shopName",
            width: 125,
            key: "shopName"
          },
          {
            title: "创建人",
            dataIndex: "createByName",
            width: 125,
            key: "createByName"
          },
          {
            title: "创建人账号",
            dataIndex: "phone",
            width: 125,
            key: "phone"
          },
          // {
          //   title: "身份类型",
          //   dataIndex: "createUserType",
          //   width: 155,
          //   key: "createUserType"
          // },
          {
            title: "审核状态",
            dataIndex: "auditStatus",
            width: 125,
            key: "auditStatus",
            customRender: (text, record) => findDictNameByValue('WECHAT_AUDIT_STATUS', text)
          },
          {
            title: "商品状态",
            dataIndex: "productStatus",
            width: 125,
            key: "productStatus",
            customRender: (text, record) => findDictNameByValue('LIVE_GOODS_AUDIT', text)
          },
          {
            title: "操作",
            dataIndex: "operation",
            fixed: 'right',
            width: 185,
            scopedSlots: { customRender: "operation" },
          }
        ]
      }
    },
    watch: {},
    computed:{
      // 用户信息
      userInfo(){
        return this.$store.getters.userInfo || {};
      }
    },
    created() {
      this.getProductGroup();//分组
    },
    mounted() {},
    methods: {
      // 切换直播平台
      appIdChange(val) {
        this.activeAppId = val
        if(val == '100000054') {
          this.form.setFieldsValue({
            blongShop: 1,
          });
        }
      },
      // 切换所属店铺
      blongShopChange(val) {
        this.activeBlongShop = val
      },
      //商品分组
      async getProductGroup(){
        let res=await this.$get('/goods/group/tree',{
          shopId:this.userInfo.shopId || ''
        },false,true);
        if(res && res.returnCode=='1000'){
          this.productGroupList=res.dataInfo || [];
        }
        else {
          this.productGroupList=[];
        }
      },
      // 添加商品
      creatLive() {
        this.handle = 'add';
        this.$router.push({
          name:'MarketingLiveCommodityPagesCommodityForm',
          query: {
            handle: 'add',
            blong: this.activeBlongShop,
            appId: this.$refs.searchtable.searchParams.appId
          }
        })
      },
      // type view 查看   edit 编辑
      checkLiveRoom(record, type) {
        this.handle = type;
        this.$router.push({
          name:'MarketingLiveCommodityPagesCommodityForm',
          query: {
            handle: type,
            id: record.goodsId,
            blong: this.activeBlongShop,
            appId: this.$refs.searchtable.searchParams.appId,
            current: this.$refs.searchtable.pagination.current
          }
        })
      },
      // 删除直播间商品
      deleteLive(record) {
        if(!record) {
          this.$message.warning('请先选择一项后再进行操作！');
          return
        }
        let url='',params={}
        if(record.remark == 1){
          url = '/product/deleteProduct'
          params={
            appId: this.$refs.searchtable.searchParams.appId,
            id: record.id,
            goodsId: record.goodsId
          }
        } else {
          url = '/product/delete'
          params={
            removeIds: [record.id]
          }
        }
        let _this = this;
        this.$confirm({
          title: '删除操作',
          content: '是否确定删除该商品，删除后将不可恢复！',
          okText: '确认删除',
          cancelText: '取消',
          onOk() {
            _this.$post(url,
                params,
                { baseURL: `${location.origin}/goldenhome/gh/live/admin` }).then((res) => {
              if (res && res.returnCode == 1000) {
                _this.$message.success('删除成功');
                _this.$refs.searchtable.refreshTable();
              }
            });
          },
          onCancel() {},
        });
      },
      // 同步商品数据
      syncLive(records) {
        let _this = this
        let goodsIds = records.map((item) => {
          return item.goodsId
        })
        let params = {}
        params.goodsIds = goodsIds
        params.appId = this.$refs.searchtable.searchParams.appId
        this.$post('/product/syncselect',
            params,
            { baseURL: `${location.origin}/goldenhome/gh/live/admin` }).then((res) => {
          if (res && res.returnCode == 1000) {
            _this.$message.success('同步成功');
            _this.$refs.searchtable.refreshTable();
          }
        });
      },
      // 审核
      browseGoods(record, type) {
        let _this = this
        let params = {}
        if (type === '1') {
          let url = ''
          if(record.remark == 1) {
            params.goodsId = record.goodsId
            params.appId = this.$refs.searchtable.searchParams.appId
            url = '/product/retryaudit'
          } else {
            url = '/product/addProduct'
            params = record
          }
          this.$post(url,
              params,
              { baseURL: `${location.origin}/goldenhome/gh/live/admin` }).then((res) => {
            if (res && res.returnCode == 1000) {
              _this.$message.success('操作成功');
              _this.$refs.searchtable.refreshTable();
            }
          });
        } else {
          params.goodsId = record.goodsId
          params.appId = this.$refs.searchtable.searchParams.appId
          params.auditId = record.auditId
          this.$post('/product/resetaudit',
              params,
              { baseURL: `${location.origin}/goldenhome/gh/live/admin` }).then((res) => {
            if (res && res.returnCode == 1000) {
              _this.$message.success('操作成功');
              _this.$refs.searchtable.refreshTable();
            }
          });
        }
      }
    }
  }
</script>

<style scoped lang="less">

</style>
